
package com.wodan.zhongjinjicang.controller;

import com.alibaba.fastjson.JSONObject;
import com.wodan.zhongjinjicang.common.constants.ClientApiConstants;
import com.wodan.zhongjinjicang.enums.BusinessErrorEnum;
import com.wodan.zhongjinjicang.service.ServiceTemplate;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 公共控制器
 */
@Controller
@RequestMapping("/sms")
public class SmsController {

	public static Logger logger = LoggerFactory.getLogger(SmsController.class);

	@Autowired
	private ServiceTemplate serviceTemplate;

	@RequestMapping(value = "/{serviceName}", method = {RequestMethod.POST })
	@ResponseBody
   public JSONObject testCommon(HttpServletRequest request, HttpServletResponse response,
				   @PathVariable String serviceName) {

		String sessionId = request.getParameter("sessionId");
		//默认值，防止空异常，后续会做处理
		if(StringUtils.isBlank(sessionId)){
			sessionId = "123456";
		}
		String message = request.getParameter("message");

		logger.debug("客户端传入 sessionId:" + sessionId);

		JSONObject jo = serviceTemplate.executeJsonObject(serviceName, request,
								response, sessionId, message, new ServiceTemplate.CallbackHandler() {
								@Override
								public JSONObject buildBizParams(HttpServletRequest request,
																 HttpServletResponse response, String sessionId,
																 String message) {
									try {
										return (JSONObject) JSONObject.parse(message);
									}catch(Exception e){
										JSONObject respContent = new JSONObject();
										respContent.put(ClientApiConstants.CODE, BusinessErrorEnum.ERROR.getCode());
										respContent.put(ClientApiConstants.MSG, "JSON解析失败,请检查JSON格式");
										respContent.put(ClientApiConstants.Data, new JSONObject());
										return respContent;
									}
								}
						});
		System.out.println(jo.toString());
		return jo;

	}

}

